import uuid

from elasticsearch import Elasticsearch

from utils import date_util

es_service = Elasticsearch(["127.0.0.1"], http_auth=("elastic", "elastic"), port=9200)


class ES:
    def __init__(self):
        self.index_name: str = "stock-monitor"
        self.module: str = None
        self.title: str = None  # 标题
        self.traceId: str = None

    # 插入数据
    def index(self, body: dict):
        if self.traceId is None:
            self.traceId = uuid.uuid4()
        if self.module is not None:
            body['module'] = self.module
        if self.title is not None:
            body['title'] = self.title
        body['traceId'] = self.traceId
        body['timestamp'] = date_util.get_timestamp_now()
        body['datetime'] = date_util.get_date_time()
        es_service.index(index=self.index_name, body=body)

    # 查询全部
    def match_all(self):
        query = {"query": {"match_all": {}}}
        try:
            return self.get_source(es_service.search(index=self.index_name, body=query))
        except Exception as e:
            return None

    # 查询数据 - 精确查询
    def search_term(self, term: dict):
        query = {"query": {"term": term}}
        try:
            return self.get_source(es_service.search(index=self.index_name, body=query))
        except Exception as e:
            return None

    # 查询数据 - 排序查询
    def search_sort(self, term: dict, sort: list):
        query = {"query": {"term": term}, "sort": sort}
        try:
            return self.get_source(es_service.search(index=self.index_name, body=query))
        except Exception as e:
            return None

    # 范围查询 只会查询出10条
    def search_range(self, key: str, beg: int, end: int):
        if end < beg:
            return None
        query = {"query": {"range": {key: {"gte": beg, "lte": end}}}}
        try:
            return self.get_source(es_service.search(index=self.index_name, body=query))
        except Exception as e:
            return None

    def get_sort_body(self, sort: list, sort_key: str, asc: str):
        sort.append({sort_key: {"order": asc}})
        return sort

    # 获取匹配项
    def get_hits(self, result):
        return result.get('hits').get('hits')

    # 获取匹配项
    def get_source(self, result):
        hits = self.get_hits(result)
        source = []
        for hit in hits:
            source.append(hit.get('_source'))
        return source

    # 获取匹配项
    def get_source_page(self, result):
        hits = self.get_hits(result)
        source = []
        for hit in hits:
            source.append(hit.get('_source'))
        return source

    # 根据id删除数据
    def delete_by_id(self, id):
        return es_service.delete(index=self.index_name, id=id)

    # term 删除
    def delete_match(self, match):
        query = {"query": {"match": match}}
        return es_service.delete_by_query(index=self.index_name, body=query)

    # term 删除
    def delete_match_all(self, match):
        query = {"query": {"match": match}}
        return es_service.delete_by_query(index=self.index_name, body=query, wait_for_completion=False)


if __name__ == '__main__':
    print('start')
    es = ES()
    # es.index({"first_name": "zhong", "last_name": "zhong", 'age': 30})
    # print(es.search_term({'age': 22}))
    # print(es.delete_by_id('-9gI-30BUs2omrtKYOJF'))
    print(es.delete_match({'age': 30}))
    # es.index(index="megacorp",
    #          body={"first_name": "xiao", "last_name": "xiao", 'age': 25, 'about': 'I love to go rock climbing',
    #                'interests': ['game', 'play']})
    # es.index(index="megacorp", id=4,
    #          body={"first_name": "xiao", "last_name": "wu", 'age': 66, 'about': 'I love to go rock climbing',
    #                'interests': ['sleep', 'eat']})
    # query = {
    #     "query": {
    #         "match_all": {}
    #     }
    # }
    # query = {
    #     "query": {
    #         "term": {
    #             'age': 25
    #         }
    #     }
    # }
    # result = es.search(index="megacorp", body=query)
    # print(result)
# {'_index': 'megacorp',
#  '_type': '_doc',
#  '_id': '3oXEzm4BAZBCZGyZ2R40',
#  '_version': 1,
#  'result': 'created',
#  '_shards': {'total': 2, 'successful': 1, 'failed': 0},
#  '_seq_no': 1,
#  '_primary_term': 2}
# 指定IDwu

# {'_index': 'megacorp',
#  '_type': '_doc',
#  '_id': '4',
#  '_version': 1,
#  'result': 'created',
#  '_shards': {'total': 2, 'successful': 1, 'failed': 0},
#  '_seq_no': 5,
#  '_primary_term': 2}
